<script setup>
import { ref } from 'vue'
import { useRouter } from "vue-router"
import { showToast } from 'vant'
import { publishProductApi } from '../api/products'

const router = useRouter()

// 定义表单数据
const productName = ref('')
const uploader = ref('')
const showImage = ref(false) // 控制是否显示图片
const productDescription = ref('') // 商品描述
const productPrice = ref('') // 商品价格
const productStock = ref('') // 商品库存
const productCategory = ref('') // 商品分类

// 商品分类选项
const categoryOptions = [
  { text: '电子产品', value: '电子产品' },
  { text: '美妆', value: '美妆' },
  { text: '家居', value: '家居' },
  { text: '衣服', value: '衣服' },
  { text: '玩具', value: '玩具' }
]

const onClickLeft = () => {
  router.push("/")
}

// 表单提交函数 (添加 async 关键字)
const onSubmit = async () => {
  if (!productName.value || !uploader.value || !productDescription.value ||
      !productPrice.value || !productStock.value || !productCategory.value) {
    showToast('请填写完整信息')
    return
  }

  // 验证价格和库存是否为有效数字
  const price = parseFloat(productPrice.value)
  const stock = parseInt(productStock.value)

  if (isNaN(price) || price <= 0) {
    showToast('请输入有效的价格')
    return
  }

  if (isNaN(stock) || stock < 0) {
    showToast('请输入有效的库存数量')
    return
  }

  try {
    // 调用API发布商品
    const res = await publishProductApi({
      name: productName.value,
      image_url: uploader.value,
      description: productDescription.value,
      price: price,
      stock: stock,
      category: productCategory.value
    })

    if (res.success) {
      showToast('发布成功')
      // 发布成功后重置表单
      resetForm()
      // 跳转到首页查看发布结果
      router.push("/")
    } else {
      showToast('发布失败: ' + res.message)
    }
  } catch (error) {
    console.error('发布商品时出错:', error)
    showToast('发布失败，请重试')
  }
}

// 重置表单
const resetForm = () => {
  productName.value = ''
  uploader.value = ''
  showImage.value = false
  productDescription.value = ''
  productPrice.value = ''
  productStock.value = ''
  productCategory.value = ''
}

// 图片预览功能
const previewImage = () => {
  if (!uploader.value) {
    showToast('请先输入图片链接')
    return
  }

  // 自动补全http协议
  let imageUrl = uploader.value
  if (!/^https?:\/\//i.test(imageUrl)) {
    imageUrl = `https://${imageUrl}`
  }

  // 更新uploader的值
  uploader.value = imageUrl

  // 显示图片区域
  showImage.value = true

  // 验证图片是否能正常加载
  const img = new Image()
  img.onload = () => {
    showToast('图片加载成功')
  }
  img.onerror = () => {
    showToast('图片加载失败，请检查链接')
    showImage.value = false
  }
  img.src = imageUrl
}
</script>

<template>
  <div class="publish-container">
    <van-nav-bar title="发布" left-text="返回首页" left-arrow @click-left="onClickLeft" />

    <div class="form-wrapper">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <!-- 商品名称 -->
          <van-field
            v-model="productName"
            name="productName"
            label="商品名称"
            placeholder="请输入商品名称"
            :rules="[{ required: true, message: '请输入商品名称' }]"
          />

          <!-- 图片链接 -->
          <van-field
            v-model="uploader"
            name="uploader"
            label="图片链接"
            placeholder="请输入图片链接"
            :rules="[{ required: true, message: '请输入图片链接' }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                @click="previewImage"
                :disabled="!uploader"
              >
                预览
              </van-button>
            </template>
          </van-field>

          <!-- 图片预览区域（只在点击预览后显示） -->
          <div v-if="showImage" style="padding: 16px; text-align: center">
            <img
              :src="uploader"
              style="max-width: 100%; max-height: 300px; border-radius: 4px"
              alt="图片预览"
            >
          </div>

          <!-- 商品描述 -->
          <van-field
            v-model="productDescription"
            name="productDescription"
            label="商品描述"
            placeholder="请输入商品描述"
            type="textarea"
            rows="2"
            autosize
            :rules="[{ required: true, message: '请输入商品描述' }]"
          />

          <!-- 商品价格 -->
          <van-field
            v-model="productPrice"
            name="productPrice"
            label="商品价格"
            placeholder="请输入商品价格"
            type="number"
            :rules="[
              { required: true, message: '请输入商品价格' },
              { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式' }
            ]"
          >
            <template #right-icon>
              <span>元</span>
            </template>
          </van-field>

          <!-- 商品库存 -->
          <van-field
            v-model="productStock"
            name="productStock"
            label="商品库存"
            placeholder="请输入商品库存"
            type="number"
            :rules="[
              { required: true, message: '请输入商品库存' },
              { pattern: /^[1-9]\d*$/, message: '请输入正确的库存数量' }
            ]"
          >
            <template #right-icon>
              <span>件</span>
            </template>
          </van-field>

          <!-- 商品分类（下拉菜单形式） -->
          <van-field name="productCategory" label="商品分类" required>
            <template #input>
              <van-dropdown-menu>
                <van-dropdown-item
                  v-model="productCategory"
                  :options="categoryOptions"
                />
              </van-dropdown-menu>
            </template>
          </van-field>
        </van-cell-group>

        <!-- 提交按钮 -->
        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.publish-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.form-wrapper {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20px;
}

// 自定义样式
.van-field__button {
  display: flex;
  align-items: center;
}

// 图片预览容器的边框
img {
  border: 1px solid #eee;
  padding: 4px;
  box-sizing: border-box;
}

// 下拉菜单样式调整
:deep(.van-dropdown-menu) {
  box-shadow: none;
  flex: 1;
}

:deep(.van-dropdown-menu__bar) {
  box-shadow: none;
  background-color: transparent;
  height: auto;
  min-height: 24px;
}

:deep(.van-dropdown-menu__item) {
  justify-content: flex-end;
}

:deep(.van-dropdown-menu__title) {
  padding: 0;
  color: #333;
  font-size: 14px;
}

// 提交按钮容器确保不被遮挡
:deep(.van-submit-bar) {
  bottom: 0;
}
</style>